package com.ywjt.platformbusiness.home.activity;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.ywjt.platformbusiness.R;
import com.ywjt.platformbusiness.base.BaseActivity;
import com.ywjt.platformbusiness.base.MyApp;
import com.ywjt.platformbusiness.util.SPUtils;
import com.ywjt.platformbusiness.util.SoftKeyboardUtils;
import com.ywjt.platformbusiness.widget.FlowViewGroup;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Activity_Search_History extends BaseActivity implements View.OnClickListener {
    private FlowViewGroup mFlowViewGroup;
    private ImageView ivBack;
    private TextView tvClear;
    private TextView tvSearch;
    private EditText etSearch;
    private String keys="";
    private TextView tvNodata;

    public static void actionStart(Context context) {
        Intent intent = new Intent(context, Activity_Search_History.class);
        context.startActivity(intent);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.ivBack:
                finish();
                break;
            case R.id.tvClear:
                //清除搜索历史
                clearHistory();
                mFlowViewGroup.removeAllViews();
                break;
            case R.id.tvSearch:
                SoftKeyboardUtils.hideSoftKeyboard(this);
                if(SPUtils.getSharedBooleanData(getContext(),"isLogin")){
                    if(keys.equals("")||keys.length()==0){
                        //搜索内容为空
                        Toast.makeText(getContext(),"搜索内容不能为空",Toast.LENGTH_SHORT).show();
                    }else {
                        saveSearchHistory(keys);
                       // Activity_Search.actionStart(getContext(),keys);
                    }
                }else {
                    Toast.makeText(getContext(),"你还没有登录请先去登录",Toast.LENGTH_SHORT).show();
                }
                break;
        }
    }


    @Override
    protected void init(Bundle savedInstanceState) {
        setAndroidNativeLightStatusBar(true);
    }

    @Override
    protected int setLayoutResourceID() {
        return R.layout.activity_search_history;
    }

    @Override
    protected void initView() {
        mFlowViewGroup = (FlowViewGroup) findViewById(R.id.flowlayout);
        tvNodata=findViewById(R.id.tvNodata);
        tvSearch=findViewById(R.id.tvSearch);
        tvSearch.setOnClickListener(this::onClick);
        ivBack=findViewById(R.id.ivBack);
        ivBack.setOnClickListener(this::onClick);
        tvClear=findViewById(R.id.tvClear);
        tvClear.setOnClickListener(this::onClick);
        etSearch=findViewById(R.id.etSearch);
        etSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                try {
                    keys = charSequence.toString().trim();
                } catch (Exception e) {
                    keys = "";
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
        etSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) {
                if (i == EditorInfo.IME_ACTION_SEARCH) {
                    if(SPUtils.getSharedBooleanData(getContext(),"isLogin")){
                        if(keys.equals("")||keys.length()==0){
                            //搜索内容为空
                            Toast.makeText(getContext(),"搜索内容不能为空",Toast.LENGTH_SHORT).show();
                        }else {
                            saveSearchHistory(keys);
                           // Activity_Search.actionStart(getContext(),keys);
                        }
                    }else {
                        Toast.makeText(getContext(),"你还没有登录请先去登录",Toast.LENGTH_SHORT).show();
                    }
                    return true;
                }
                return false;

            }});
    }


    public void clearHistory(){
        SharedPreferences sp = MyApp.context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        editor.putString(SEARCH_HISTORY,"");
        editor.commit();

    }

    @Override
    protected void initData() {
        //获取个人搜索记录数据
        getSearchHistory();
    }

    @Override
    protected int getTitleBarType() {
        return TITLEBAR_NULL;
    }

    private final static String PREFERENCE_NAME = "superservice_ly";
    private final static String SEARCH_HISTORY="linya_history";
    // 保存搜索记录
    public  void saveSearchHistory(String inputText) {
        SharedPreferences sp = MyApp.context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
        if (TextUtils.isEmpty(inputText)) {
            return;
        }
        String longHistory = sp.getString(SEARCH_HISTORY, "");  //获取之前保存的历史记录
        String[] tmpHistory = longHistory.split(","); //逗号截取 保存在数组中
        List<String> historyList = new ArrayList<String>(Arrays.asList(tmpHistory)); //将改数组转换成ArrayList
        SharedPreferences.Editor editor = sp.edit();
        if (historyList.size() > 0) {
            //1.移除之前重复添加的元素
            for (int i = 0; i < historyList.size(); i++) {
                if (inputText.equals(historyList.get(i))) {
                    historyList.remove(i);
                    break;
                }
            }
            historyList.add(0, inputText); //将新输入的文字添加集合的第0位也就是最前面(2.倒序)
            if (historyList.size() > 10) {
                historyList.remove(historyList.size() - 1); //3.最多保存10条搜索记录 删除最早搜索的那一项
            }
            //逗号拼接
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < historyList.size(); i++) {
                sb.append(historyList.get(i) + ",");
            }
            //保存到sp
            editor.putString(SEARCH_HISTORY, sb.toString());
            editor.commit();
        } else {
            //之前未添加过
            editor.putString(SEARCH_HISTORY, inputText + ",");
            editor.commit();
        }
        getSearchHistory();
    }
    //获取搜索记录
    public void getSearchHistory(){
        SharedPreferences sp = MyApp.context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
        String longHistory =sp.getString(SEARCH_HISTORY, "");
        String[] tmpHistory = longHistory.split(","); //split后长度为1有一个空串对象
        List<String> historyList = new ArrayList<String>(Arrays.asList(tmpHistory));
        if (historyList.size() == 1 && historyList.get(0).equals("")) { //如果没有搜索记录，split之后第0位是个空串的情况下
            historyList.clear();  //清空集合，这个很关键
        }

        mFlowViewGroup.removeAllViews();
        TextView tv;
        if(historyList.size()>0){
            tvNodata.setVisibility(View.GONE);
            for ( int i=0;i<historyList.size();i++){
                View view= LayoutInflater.from(Activity_Search_History.this).
                        inflate(R.layout.item_flow,mFlowViewGroup,false);
                tv=view.findViewById(R.id.text);
                tv.setText(historyList.get(i));
                int finalPosi = i;
                view.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        keys=historyList.get(finalPosi);
                        etSearch.setText(keys);
                       // Activity_Search.actionStart(getContext(),keys);
                    }
                });
                mFlowViewGroup.addView(view);
            }
        }else {
            tvNodata.setVisibility(View.VISIBLE);
        }
    }
}
